package com.openbravo.pos.sales;

import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;

import javax.swing.SwingUtilities;

import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.swing.dialog.AbstractKeyBoardJDialog;

import com.openbravo.bean.crm.physicalbond.PhysicalBond;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.format.Formats;


import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;

import com.openbravo.pos.base.AppLocal;
import net.sourceforge.jtimepiece.TimeUtil;

import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.awt.Insets;
import javax.swing.border.TitledBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JPhysicalBondDialog extends AbstractKeyBoardJDialog {


    I_DataLogicSales dlSales;

    /**
     * Creates new form JChangeRateDialog
     *
     * @wbp.parser.constructor
     */
    public JPhysicalBondDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * Creates new form JProductLineKeyBoardEdit
     */
    private JPhysicalBondDialog(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        m_jButtonOK = new javax.swing.JButton();
        m_jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(389, 240));
        setResizable(false);

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.PAGE_AXIS));

        getContentPane().add(jPanel4, java.awt.BorderLayout.CENTER);

        panel = new JPanel();
        jPanel4.add(panel);
        panel.setLayout(new BorderLayout(0, 0));
        jPanel2 = new javax.swing.JPanel();
        jPanel2.setPreferredSize(new Dimension(10, 40));
        panel.add(jPanel2, BorderLayout.NORTH);
        jPanel3 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jLabel8.setFont(new Font("宋体", Font.PLAIN, 20));
        jPriceRant = new com.openbravo.editor.JEditorIntegerPositive();
        jPriceRant.setFont(new Font("宋体", Font.PLAIN, 20));

        jPanel2.setLayout(new java.awt.BorderLayout());
        jPanel3.setLayout(new BorderLayout(0, 0));

        jLabel8.setText(AppLocal.getIntString("label.CustomerStoreValueCard.cardNum")); // NOI18N
        jLabel8.setPreferredSize(new java.awt.Dimension(80, 25));
        jPanel3.add(jLabel8, BorderLayout.WEST);
        jPanel3.add(jPriceRant, BorderLayout.CENTER);

        jPanel2.add(jPanel3, java.awt.BorderLayout.CENTER);

        btnNewButton = new JButton("");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                enterKeyProc();
            }
        });
        btnNewButton.setPreferredSize(new Dimension(70, 9));
        btnNewButton.setMargin(new Insets(0, 0, 0, 0));
        btnNewButton.setFocusPainted(false);
        btnNewButton.setFocusTraversalKeysEnabled(false);
        btnNewButton.setFocusable(false);
        btnNewButton.setIcon(new ImageIcon(JPhysicalBondDialog.class.getResource("/com/openbravo/images/search22.png")));
        jPanel3.add(btnNewButton, BorderLayout.EAST);
        m_jKeys = new com.openbravo.editor.JEditorKeys();
        panel.add(m_jKeys, BorderLayout.EAST);

        panel_2 = new JPanel();
        panel.add(panel_2, BorderLayout.CENTER);
        panel_2.setLayout(new BorderLayout(0, 0));

        panel_1 = new JPanel();
        panel_2.add(panel_1, BorderLayout.NORTH);
        panel_1.setRequestFocusEnabled(false);
        panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));

        label = new JLabel("有效期");
        panel_1.add(label);

        lblVilaDate = new JTextField("2012-10-11");
        lblVilaDate.setFont(new Font("宋体", Font.PLAIN, 20));
        lblVilaDate.setEditable(false);
        lblVilaDate.setHorizontalAlignment(SwingConstants.RIGHT);
        panel_1.add(lblVilaDate);

        lblNewLabel = new JLabel("校验码");
        panel_1.add(lblNewLabel);

        lblValidityCode = new JTextField("");
        lblValidityCode.setFont(new Font("宋体", Font.PLAIN, 20));
        lblValidityCode.setEditable(false);
        lblValidityCode.setHorizontalAlignment(SwingConstants.RIGHT);
        panel_1.add(lblValidityCode);

        textProductDialy = new JTextPane();
        textProductDialy.setBorder(new TitledBorder(null, "\u5BF9\u6362\u660E\u7EC6", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        panel_2.add(textProductDialy);
        textProductDialy.setFocusable(false);
        textProductDialy.setEditable(false);

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
        m_jButtonOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel1.add(m_jButtonOK);

        m_jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        m_jButtonCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N
        m_jButtonCancel.setFocusPainted(false);
        m_jButtonCancel.setFocusable(false);
        m_jButtonCancel.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonCancel.setRequestFocusEnabled(false);
        m_jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonCancelActionPerformed(evt);
            }
        });
        jPanel1.add(m_jButtonCancel);

        getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width - 230) / 2, (screenSize.height - 356) / 2, 443, 356);
    }// </editor-fold>//GEN-END:initComponents

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonOKActionPerformed
        try {
            dlSales.physicalBondPayment(locaId, physicaBond);
            new MessageInf(MessageInf.SGN_SUCCESS, "领用成功，谢谢").show(this);
            physicaBond = null;
            reFlush();
        } catch (BasicException e) {
            e.printStackTrace();
            new MessageInf(e).show(this);
        }
    }//GEN-LAST:event_m_jButtonOKActionPerformed

    private void m_jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonCancelActionPerformed
        dispose();
    }//GEN-LAST:event_m_jButtonCancelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private com.openbravo.editor.JEditorIntegerPositive jPriceRant;
    private javax.swing.JButton m_jButtonCancel;
    private javax.swing.JButton m_jButtonOK;
    private com.openbravo.editor.JEditorKeys m_jKeys;
    private JPanel panel;
    private JPanel panel_1;
    private JLabel label;
    private JTextPane textProductDialy;
    private JTextField lblVilaDate;
    // End of variables declaration//GEN-END:variables

    String locaId;
    PhysicalBond physicaBond;

    @Override
    protected void enterKeyProc() {
        if (m_jButtonOK.isEnabled())
            m_jButtonOKActionPerformed(null);
        else {
            String msg = null;
            try {
                physicaBond = dlSales.findPhysicalBondByCard(jPriceRant.getText());
            } catch (BasicException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (physicaBond != null) {
                switch (physicaBond.getState()) {
                    case PhysicalBond.STATE_Invalid:
                        msg = AppLocal.getIntString("label.Voucher.state.Invalid");
                        break;
                    case PhysicalBond.STATE_Loss:
                        msg = AppLocal.getIntString("label.Voucher.state.Loss");
                        break;
                    case PhysicalBond.STATE_Unknown:
                        msg = AppLocal.getIntString("label.Voucher.state.Unknown");
                        break;
                    case PhysicalBond.STATE_Used:
                        msg = AppLocal.getIntString("label.Voucher.state.Used");
                        break;
                    case PhysicalBond.STATE_Back:
                        msg = AppLocal.getIntString("label.Voucher.state.Back");
                        break;
                    case PhysicalBond.STATE_UseAble:
                        if (TimeUtil.isAfter(physicaBond.getValidityDate(), new Date()))
                            msg = AppLocal.getIntString("label.Voucher.state.Invalid");
                }
            } else {
                msg = "未找到对应的卡";
            }

            if (msg != null) {
                physicaBond = null;
                new MessageInf(MessageInf.SGN_WARNING, msg).show(this);
            }
            reFlush();
        }
    }


    private void reFlush() {
        if (physicaBond == null) {
            jPriceRant.reset();
            lblVilaDate.setText(null);
            lblValidityCode.setText(null);
            textProductDialy.setText(null);
            m_jButtonOK.setEnabled(false);
        } else {
            lblVilaDate.setText(Formats.TIMESTAMP.formatValue(physicaBond.getValidityDate()));
            lblValidityCode.setText(physicaBond.getValidityCode());
            textProductDialy.setText(physicaBond.getProductId());
            m_jButtonOK.setEnabled(true);
        }
        jPriceRant.activate();
    }

    @Override
    protected void escapeKeyProc() {
        dispose();
    }

    @Override
    protected void upKeyProc() {
    }

    @Override
    protected void downKeyProc() {

    }


    public static JPhysicalBondDialog getDialog(Component parent, I_DataLogicSales dlSales, String locaId) {
        Window window = SwingUtilities.getWindowAncestor(parent);
        JPhysicalBondDialog myMsg;
        if (window instanceof Frame) {
            myMsg = new JPhysicalBondDialog((Frame) window, true);
        } else {
            myMsg = new JPhysicalBondDialog((Dialog) window, true);
        }
        myMsg.init(dlSales, locaId);
        myMsg.applyComponentOrientation(parent.getComponentOrientation());
        return myMsg;
    }

    private void init(I_DataLogicSales dlSales, String locaId) {
        this.locaId = locaId;
        this.dlSales = dlSales;
        jPriceRant.addPropertyChangeListener("Edition", new RecalculatePriceRant());
        jPriceRant.addEditorKeys(m_jKeys);
        jPriceRant.activate();
        getRootPane().setDefaultButton(m_jButtonOK);
    }

    private class RecalculatePriceRant implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            m_jButtonOK.setEnabled(false);
        }
    }

    private JLabel lblNewLabel;
    private JTextField lblValidityCode;
    private JPanel panel_2;
    private JButton btnNewButton;

}
